package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.car.DisountCarDetailAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.imageload.ImageLoad;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.JSONUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 新车详情
 */
public class NewCarDetailActivity extends BaseActivity implements View.OnClickListener {

    String carid;

    //贷款选项
    LinearLayout loanOtionsV;

    //官方价格
    TextView priceT;

    ViewPager viewPager;

    TextView titleT;

    //折扣价
    TextView discount_priceT;

    //首付
    TextView low_month_payT;

    TextView colorT;

    //购买新车按钮
    TextView buyT;

    //购买新车时需要传递的数据
    String detailJo;

    JSONObject shareJo;

    ImageView right_fenxiangI;

    JSONObject jsonProduct;

    TextView configT;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_car_detail);

        initView();
    }

    private void initView() {
        setTitle("新车详情");
        carid = getIntent().getStringExtra("carid");
        loanOtionsV = (LinearLayout) findViewById(R.id.loan_opotions);
        priceT = (TextView) findViewById(R.id.price);
        viewPager = (ViewPager) findViewById(R.id.guidePages);
        titleT = (TextView) findViewById(R.id.title);
        discount_priceT = (TextView) findViewById(R.id.discount_price);
        low_month_payT = (TextView) findViewById(R.id.low_month_pay);
        colorT = (TextView) findViewById(R.id.color);
        buyT = (TextView) findViewById(R.id.buy);
        buyT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(NewCarDetailActivity.this, SubscribeNewCarActivity.class);
                if (!TextUtils.isEmpty(detailJo)) {
                    it.putExtra("detail", detailJo.toString());
                    it.putExtra("carid", carid);
                    startActivity(it);
                }
            }
        });

        findViewById(R.id.tel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "4000253500"));
                startActivity(intent);
            }
        });

        configT = (TextView) findViewById(R.id.config);

        //查看车辆详细参数
        configT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewCarDetailActivity.this, NewCarAcitivity.class);
                intent.putExtra("json_data", jsonProduct.toString());
                intent.putExtra("from", "newcar");
                startActivity(intent);
            }
        });


        right_fenxiangI = (ImageView) findViewById(R.id.right_fenxiang);
        right_fenxiangI.setImageResource(R.drawable.share);
        right_fenxiangI.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share();
            }
        });
        getData();
    }


    private void getData() {
        showProgressDialog();
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
            }


            @Override
            public void onDataJsonUpdate(String json) {

                try {

                    JSONObject jo = new JSONObject(json);
                    jsonProduct = jo.getJSONObject("configs");
                    JSONArray paramsArray = jsonProduct.getJSONArray("params");
                    JSONArray configsArray = jsonProduct.getJSONArray("config");
                    if (paramsArray.length() == 0 && configsArray.length() == 0) {
                        configT.setVisibility(View.GONE);
                    }
                    String image_url = jo.getString("image_url");

                    if (!TextUtils.isEmpty(image_url)) {
                        String[] mProductImgsUrls = new String[1];
                        mProductImgsUrls[0] = image_url;
                        viewPager.setAdapter(new DisountCarDetailAdapter(mProductImgsUrls, NewCarDetailActivity.this, true));
                    }

                    priceT.setText("官方价" + jo.getString("price") + "万");
                    priceT.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    colorT.setText(jo.getString("colors"));
                    titleT.setText(jo.getString("model") + " " + jo.getString("model_detail"));
                    discount_priceT.setText(jo.getString("conc_price") + "万");
                    low_month_payT.setText("月供最低:" + jo.getString("low_month_pay") + "元");

                    JSONObject campaign_infoJo = jo.getJSONObject("campaign_info");

                    ImageView zhihuanI = (ImageView) findViewById(R.id.zhihuan);
                    ImageLoad.LoadImage(zhihuanI, campaign_infoJo.getString("replace_image_url"), NewCarDetailActivity.this);

                    ImageView liuchengI = (ImageView) findViewById(R.id.liucheng);
                    ImageLoad.LoadImage(liuchengI, campaign_infoJo.getString("buy_image_url"), NewCarDetailActivity.this);

                    shareJo = jo.getJSONObject("share");
                    right_fenxiangI.setVisibility(View.VISIBLE);

                    JSONObject detail = new JSONObject();
                    detail.put("image_url", jo.getString("image_url"));
                    detail.put("model", jo.getString("model"));
                    detail.put("model_detail", jo.getString("model_detail"));
                    String conc_price = (jo.getDouble("conc_price") * 10000) + "";
                    detailJo = detail.toString();
                    getloanoptions(conc_price);
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, 1);
        netDataJson.setUrl(NetDataJson.NEWCAR_SERVER_DOMAIN + API.new_car_detail + carid + "/");
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
    }

    //获取贷款选项
    private void getloanoptions(String money) {
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                hidenProgressDialog();
                try {
                    JSONObject jo = new JSONObject(json);
                    JSONArray jsa = jo.getJSONArray("options");
                    bindLoadOptions(jsa);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, 1);
        netDataJson.setUrl(NetDataJson.NEWCAR_SERVER_DOMAIN + API.new_car_detail_options);
        netDataJson.addParam("money", money);
        netDataJson.setUseOtherDomain(true);
        netDataJson.request("get");
    }


    private void bindLoadOptions(JSONArray jsonArray) {
        loanOtionsV.removeAllViews();
        LayoutInflater mLayoutInflater = LayoutInflater.from(NewCarDetailActivity.this);

        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jo = jsonArray.getJSONObject(i);
                View childV = mLayoutInflater.inflate(R.layout.item_loan_documents, null);
                loanOtionsV.addView(childV);
                TextView proportionT = (TextView) childV.findViewById(R.id.proportion);
                TextView month_payT = (TextView) childV.findViewById(R.id.month_pay);
                TextView monthsT = (TextView) childV.findViewById(R.id.months);
                TextView nameT = (TextView) childV.findViewById(R.id.name);
                TextView rateT = (TextView) childV.findViewById(R.id.rate);

                rateT.setText(jo.getString("rate"));
                int advance = (int)Math.rint(JSONUtil.getFloat(jo,"advance"));
                java.text.DecimalFormat df = new java.text.DecimalFormat("##,###,###");
                proportionT.setText(df.format(advance) + "元");
                month_payT.setText(jo.getString("month_pay") + "元");
                monthsT.setText(jo.getString("months") + "个月");
                nameT.setText(jo.getString("name"));

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onClick(View v) {


    }


    private void share() {
        if (shareJo != null) {
            try {
                String url = shareJo.getString("link");
                String title = shareJo.getString("title");
                String content = shareJo.getString("desc");
                UMImage image = new UMImage(NewCarDetailActivity.this, shareJo.getString("image_url"));
                new ShareAction(this).setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                        .withTitle(title)
                        .withMedia(image)
                        .withText(content)
                        .withTargetUrl(url)
                        .setCallback(umShareListener)
                        .open();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {

            Toast.makeText(NewCarDetailActivity.this, "分享成功!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(NewCarDetailActivity.this, " 分享失败!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(NewCarDetailActivity.this, "分享取消!", Toast.LENGTH_SHORT).show();
        }
    };
}
